package com.eyas.business.service.RecordInfo;

import com.eyas.business.config.webmvc.exception.custom.uncheck.EyasBusinessException;
import com.eyas.business.model.jdbcEntity.table.RecordAndCoach;
import com.eyas.business.model.jdbcEntity.table.RecordInfo;
import com.eyas.business.model.pojo.recordinfo.PageQueryResult;
import com.eyas.business.model.pojo.recordinfo.QueryParamDTO;
import com.eyas.core.model.page.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import static com.eyas.core.jdbc.utils.CommonJdbcUtils.commonJdbcUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Auther: 王龙龙
 * @Date: 2019/3/11 18:44
 * @Description:
 */
@Service
@Transactional
public class RecordInfoServiceImpl implements RecordInfoService {
    @Override
    public PageResult<PageQueryResult> queryRecordInfoForPage(QueryParamDTO queryParamDTO, int page, int limit) {
        StringBuffer stringBuffer = new StringBuffer("");
        stringBuffer.append(" select a.recordid,a.classid,e.coachid,d.keyworlds as statustext,c.classname,b.coachname, ")
                .append(" (select keyworlds from keyworldsinfo where dcode='AGERANGE' and keycode=a.agerange) as agerange, ")
                .append(" a.address,a.starttime,a.begintime,a.endtime,a.maxnum,a.currnum,a.recordhour,a.status, ")
                .append(" (select group_concat(g.coachname separator ';') from recordandcoach f,coachinfo g where f.recordid=a.recordid and f.coachflag='2' and f.coachid=g.coachid) as assistantsname ")
                .append(" from recordinfo a,coachinfo b,classinfo c,keyworldsinfo d,recordandcoach e ")
                .append(" where e.coachid=b.coachid ")
                .append(" and a.classid=c.classid ")
                .append(" and d.dcode='RECORDSTATUS' and d.keycode=a.status ")
                .append(" and a.starttime=? ")
                .append(" and e.recordid=a.recordid and e.coachflag='1' ");
        if(queryParamDTO.getSelectdate()==null) {
            queryParamDTO.setSelectdate(new Date());
        }
        PageResult<PageQueryResult> pageResult = commonJdbcUtils.queryForPage(stringBuffer.toString(),PageQueryResult.class,page,limit,
                new SimpleDateFormat("yyyy-MM-dd").format(queryParamDTO.getSelectdate()));
        return pageResult;
    }

    @Override
    public List<PageQueryResult> queryDistinctStartTime(Integer year, Integer month) {
        Calendar calendar = Calendar.getInstance();
        if(year==null||month==null||year==0||month==0) {
            Date date = new Date();
            calendar.setTime(date);
        }else {
            calendar.set(Calendar.YEAR,year);
            calendar.set(Calendar.MONTH,month-1);
        }

        calendar.set(Calendar.DATE,1);
        Date startDate = calendar.getTime();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date endDate = calendar.getTime();
        String sql = "select distinct starttime as marktime from recordinfo where starttime >=? and starttime<=? and status<>'4'";
        SimpleDateFormat simpleDateFormat =  new SimpleDateFormat("yyyy-MM-dd");
        return commonJdbcUtils.queryList(sql,PageQueryResult.class,simpleDateFormat.format(startDate),simpleDateFormat.format(endDate));
    }

    @Override
    public PageQueryResult getRecordInfoById(Integer recordid) {
        return commonJdbcUtils.queryObject("select a.*,b.coachid from recordinfo a,recordandcoach b where a.recordid=? and a.recordid=b.recordid " +
                " and b.coachflag='1' ",PageQueryResult.class,recordid);
    }

    @Override
    public void saveRecordInfo(QueryParamDTO queryParamDTO) {
        //增加判断，begintime不能晚于endtime
        if(queryParamDTO.getBegintime().compareTo(queryParamDTO.getEndtime())>=0)
            throw new EyasBusinessException("[课程开始时间]要小于[课程结束时间]");

        /**
         * 开班成功的先决条件
         * 1、一个教练不同开班记录的上课时间不能有交叉
         */
        SimpleDateFormat simpleDateFormat1 =  new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat2 =  new SimpleDateFormat("HH:mm:ss");

        if(queryParamDTO.getRecordid()!=null&&queryParamDTO.getRecordid()!=0) {//update
            int count = commonJdbcUtils.queryObject("select count(1) from recordinfo a,recordandcoach b where a.status<>'4' " +
                            " and b.coachid=? and b.recordid=a.recordid and starttime=? and (( " +
                            " (begintime>? and begintime<?) " +
                            " or (endtime>? and endtime<?) " +
                            " or (begintime<? and endtime>?) ) or begintime=? and endtime=?) ",Integer.class,queryParamDTO.getCoachid(),simpleDateFormat1.format(queryParamDTO.getStarttime()),
                    simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                    simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                    simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                    simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()));
            if(count>1)
                throw new EyasBusinessException("主教练的时间安排出现交叉，请检查");
            RecordInfo recordInfo1 = commonJdbcUtils.queryObject("select * from recordinfo where recordid=?",RecordInfo.class,queryParamDTO.getRecordid());
            BeanUtils.copyProperties(queryParamDTO,recordInfo1,"currnum");
            commonJdbcUtils.update(recordInfo1);
            //删除上课教练和助教信息，重新插入
            commonJdbcUtils.delete("delete from recordandcoach where recordid=?",queryParamDTO.getRecordid());

            RecordAndCoach recordAndCoach_coach = new RecordAndCoach(); //主教练信息
            recordAndCoach_coach.setCoachid(queryParamDTO.getCoachid());
            recordAndCoach_coach.setRecordid(queryParamDTO.getRecordid());
            recordAndCoach_coach.setCoachflag("1");
            commonJdbcUtils.insert(recordAndCoach_coach);

            //助教信息
            if(queryParamDTO.getAssistantids()!=null&&queryParamDTO.getAssistantids().length>0) {
                for(int i=0;i<queryParamDTO.getAssistantids().length;i++) {
                    count = commonJdbcUtils.queryObject("select count(1) from recordinfo a,recordandcoach b where a.status<>'4' " +
                                    " and b.coachid=? and b.recordid=a.recordid and starttime=? and (( " +
                                    " (begintime>? and begintime<?) " +
                                    " or (endtime>? and endtime<?) " +
                                    " or (begintime<? and endtime>?) ) or begintime=? and endtime=?) ",Integer.class,queryParamDTO.getAssistantids()[i],simpleDateFormat1.format(queryParamDTO.getStarttime()),
                            simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                            simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                            simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                            simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()));
                    if(count>0)
                        throw new EyasBusinessException("助教的时间安排出现交叉，请检查");
                    RecordAndCoach recordAndCoach = new RecordAndCoach(); //助教信息
                    recordAndCoach.setCoachid(queryParamDTO.getAssistantids()[i]);
                    recordAndCoach.setRecordid(queryParamDTO.getRecordid());
                    recordAndCoach.setCoachflag("2");
                    commonJdbcUtils.insert(recordAndCoach);
                }
            }

        }else {//insert
            List<Date> dateList = new ArrayList<>();
            if(!StringUtils.hasText(queryParamDTO.getInserttype()))
                queryParamDTO.setInserttype("0");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(queryParamDTO.getStarttime());
            switch (queryParamDTO.getInserttype()) {
                case "0": //只生成一天的课程
                    dateList.add(queryParamDTO.getStarttime());
                    break;
                case "1": //生成当天和下周当天的课程
                    dateList.add(queryParamDTO.getStarttime());
                    calendar.add(Calendar.DATE,7);
                    dateList.add(calendar.getTime());
                    break;
                case "2": //生成当天和下周当天，下下周当天课程
                    dateList.add(queryParamDTO.getStarttime());
                    calendar.add(Calendar.DATE,7);
                    dateList.add(calendar.getTime());
                    calendar.add(Calendar.DATE,7);
                    dateList.add(calendar.getTime());
                    break;
                case "3": //连续生成4周的课程
                    dateList.add(queryParamDTO.getStarttime());
                    calendar.add(Calendar.DATE,7);
                    dateList.add(calendar.getTime());
                    calendar.add(Calendar.DATE,7);
                    dateList.add(calendar.getTime());
                    calendar.add(Calendar.DATE,7);
                    dateList.add(calendar.getTime());
                    break;
            }
            for(int i=0;i<dateList.size();i++) {
                int count = commonJdbcUtils.queryObject("select count(1) from recordinfo a,recordandcoach b where a.status<>'4' " +
                                " and b.coachid=? and b.coachflag='1' and b.recordid=a.recordid and starttime=? and (( " +
                                " (begintime>? and begintime<?) " +
                                " or (endtime>? and endtime<?) " +
                                " or (begintime<? and endtime>?) ) or begintime=? and endtime=?) ",Integer.class,queryParamDTO.getCoachid(),simpleDateFormat1.format(dateList.get(i)),
                        simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                        simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                        simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                        simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()));
                if(count>0)
                    throw new EyasBusinessException("在["+simpleDateFormat1.format(dateList.get(i))+"]这一天该教练的时间安排出现交叉,这次排课无效");
                RecordInfo recordInfo = new RecordInfo();
                queryParamDTO.setCurrnum(0);
                BeanUtils.copyProperties(queryParamDTO,recordInfo,"starttime");
                recordInfo.setStarttime(dateList.get(i));
                commonJdbcUtils.insert(recordInfo);

                RecordAndCoach recordAndCoach_coach = new RecordAndCoach(); //主教练信息
                recordAndCoach_coach.setCoachid(queryParamDTO.getCoachid());
                recordAndCoach_coach.setRecordid(recordInfo.getRecordid());
                recordAndCoach_coach.setCoachflag("1");
                commonJdbcUtils.insert(recordAndCoach_coach);

                //助教信息
                if(queryParamDTO.getAssistantids()!=null&&queryParamDTO.getAssistantids().length>0) {
                    for(int j=0;j<queryParamDTO.getAssistantids().length;j++) {
                        count = commonJdbcUtils.queryObject("select count(1) from recordinfo a,recordandcoach b where a.status<>'4' " +
                                        " and b.coachid=? and b.coachflag='1' and b.recordid=a.recordid and starttime=? and (( " +
                                        " (begintime>? and begintime<?) " +
                                        " or (endtime>? and endtime<?) " +
                                        " or (begintime<? and endtime>?) ) or begintime=? and endtime=?) ",Integer.class,queryParamDTO.getAssistantids()[j],simpleDateFormat1.format(dateList.get(i)),
                                simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                                simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                                simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()),
                                simpleDateFormat2.format(queryParamDTO.getBegintime()),simpleDateFormat2.format(queryParamDTO.getEndtime()));
                        if(count>0)
                            throw new EyasBusinessException("助教的时间安排出现交叉,这次排课无效");
                        RecordAndCoach recordAndCoach = new RecordAndCoach(); //助教信息
                        recordAndCoach.setCoachid(queryParamDTO.getAssistantids()[j]);
                        recordAndCoach.setRecordid(recordInfo.getRecordid());
                        recordAndCoach.setCoachflag("2");
                        commonJdbcUtils.insert(recordAndCoach);
                    }
                }
            }

        }
    }

    @Override
    public PageResult<PageQueryResult> queryRecordInfoForYK(QueryParamDTO queryParamDTO, int page, int limit) {
        StringBuffer stringBuffer = new StringBuffer("");
        stringBuffer.append(" select a.recordid,a.classid,e.coachid,d.keyworlds as statustext,c.classname,b.coachname, ")
                .append(" (select keyworlds from keyworldsinfo where dcode='AGERANGE' and keycode=a.agerange) as agerange, ")
                .append(" a.address,a.starttime,a.begintime,a.endtime,a.maxnum,a.currnum,a.recordhour,a.status ")
                .append(" from recordinfo a,coachinfo b,classinfo c,keyworldsinfo d ,recordandcoach e")
                .append(" where e.coachid=b.coachid ")
                .append(" and a.classid=c.classid ")
                .append(" and d.dcode='RECORDSTATUS' and d.keycode=a.status ")
                .append(" and e.recordid=a.recordid and e.coachflag='1' ");
        List list = new ArrayList();
        if(StringUtils.hasText(queryParamDTO.getClassname())) {
            stringBuffer.append(" and c.classname like ? ");
            list.add("%"+queryParamDTO.getClassname()+"%");
        }
        if(queryParamDTO.getStarttime()!=null) {
            SimpleDateFormat simpleDateFormat1 =  new SimpleDateFormat("yyyy-MM-dd");
            stringBuffer.append(" and a.starttime=? ");
            list.add(simpleDateFormat1.format(queryParamDTO.getStarttime()));
        }
        if(queryParamDTO.getCoachid()!=null&&queryParamDTO.getCoachid()!=0) {
            stringBuffer.append(" and e.coachid=? ");
            list.add(queryParamDTO.getCoachid());
        }
        PageResult<PageQueryResult> pageResult = commonJdbcUtils.queryForPage(stringBuffer.toString(),PageQueryResult.class,page,limit,list);
        return pageResult;
    }

    @Override
    public List<PageQueryResult> queryRecordInfoForList(Integer classid,Date selectDate) {
        StringBuffer stringBuffer = new StringBuffer("");
        stringBuffer.append(" select a.recordid,a.classid,a.recordhour,e.coachid,c.classname,b.coachname,a.details, ")
                .append(" CASE " +
                        "    WHEN a.status = '4' " +
                        "    THEN '课程取消' " +
                        "    WHEN a.starttime = DATE_FORMAT(NOW(), '%Y-%m-%d') " +
                        "    AND a.begintime <= DATE_FORMAT(NOW(), '%H:%I:%S') " +
                        "    AND a.endtime >= DATE_FORMAT(NOW(), '%H:%I:%S') " +
                        "    THEN '上课中' " +
                        "    WHEN ( " +
                        "      a.starttime = DATE_FORMAT(NOW(), '%Y-%m-%d') " +
                        "      AND a.endtime < DATE_FORMAT(NOW(), '%H:%I:%S') " +
                        "    ) " +
                        "    OR a.starttime < DATE_FORMAT(NOW(), '%Y-%m-%d') " +
                        "    THEN '课程结束' " +
                        "    ELSE d.keyworlds " +
                        "  END AS statustext, ")
                .append(" (select keyworlds from keyworldsinfo where dcode='AGERANGE' and keycode=a.agerange) as agerange, ")
                .append(" a.address,a.starttime,a.begintime,a.endtime,a.maxnum,a.currnum,a.recordhour, ")
                .append(" CASE " +
                        "    WHEN a.status = '4' " +
                        "    THEN '4' " +
                        "    WHEN a.starttime = DATE_FORMAT(NOW(), '%Y-%m-%d') " +
                        "    AND a.begintime <= DATE_FORMAT(NOW(), '%H:%I:%S') " +
                        "    AND a.endtime >= DATE_FORMAT(NOW(), '%H:%I:%S') " +
                        "    THEN '2' " +
                        "    WHEN ( " +
                        "      a.starttime = DATE_FORMAT(NOW(), '%Y-%m-%d') " +
                        "      AND a.endtime < DATE_FORMAT(NOW(), '%H:%I:%S') " +
                        "    ) " +
                        "    OR a.starttime < DATE_FORMAT(NOW(), '%Y-%m-%d') " +
                        "    THEN '3' " +
                        "    ELSE a.status " +
                        "  END AS STATUS, ")
                .append(" (select group_concat(g.coachname separator ';') from recordandcoach f,coachinfo g where f.recordid=a.recordid and f.coachflag='2' and f.coachid=g.coachid) as assistantsname ")
                .append(" from recordinfo a,coachinfo b,classinfo c,keyworldsinfo d,recordandcoach e ")
                .append(" where e.coachid=b.coachid ")
                .append(" and a.classid= ? and a.status<>'4' ")
                .append(" and a.classid=c.classid ")
                .append(" and d.dcode='RECORDSTATUS' and d.keycode=a.status ")
                .append(" and a.starttime=? ")
                .append(" and e.recordid=a.recordid and e.coachflag='1' ")
                .append(" order by a.begintime ");
        
        if(selectDate==null)
            selectDate = new Date();
        return commonJdbcUtils.queryList(stringBuffer.toString(),PageQueryResult.class,classid,
                new SimpleDateFormat("yyyy-MM-dd").format(selectDate));
    }
}
